﻿using RBAC.Infrasturcture.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RBAC.Infrasturcture.Implement
{
    /// <summary>
    /// 仓储基类
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly DBcontext context;

        public BaseRepository(DBcontext context)
        {
            this.context = context;
        }
        /// <summary>
        ///上下文
        /// </summary>
        public DBcontext DB {  get { return context; } }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public Task<int> AddAsync(T entity)
        {
            context.Set<T>().Add(entity);
            return context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public Task<int> AddRange(List<T> entity)
        {
            context.Set<T>().AddRange(entity);
            return context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除      
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>

        public Task<int> Delete(T entity)
        {
            context.Set<T>().Remove(entity);
            return context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量删除      
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public Task<int> DeleteRange(List<T> entity)
        {
            context.Set<T>().RemoveRange(entity);
            return context.SaveChangesAsync();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <returns>返回集合</returns>
        public IQueryable<T> GetAll()
        {
            return context.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回受影响行数</returns>
        public Task<int> UpdateAsync(T entity)
        {
            context.Set<T>().Update(entity);
            return context.SaveChangesAsync();
        }
    }
}
